<?php

namespace app\admin\controller;

use think\Db;

class Order extends Base
{
    public function getOrderList()
    {
        $where = [];
        input('orderSn') != null ? $where['o.orderSn'] = ['like', '%' . input('orderSn') . '%'] : true;
        input('paymentStatus') != null ? $where['o.paymentStatus'] = input('paymentStatus') : true;
        input('cancelStatus') != null ? $where['o.cancelStatus'] = input('cancelStatus') : true;

        $res = model('order')
            ->alias('o')
            ->field('o.id,o.orderSn,o.totalAmount,o.paymentStatus,o.cancelStatus,o.createTime,o.commentValue,o.commentStatus,u.name userName,u.mobile userMobile')
            ->join('user u', 'o.employeeId=u.id', 'left')
            ->order('o.cancelStatus asc, o.paymentStatus asc')
            ->where($where)
            ->paginate(10)
            ->toArray();
        $res ? $this->suc($res) : $this->err('获取订单列表失败');
    }

    //获取订单详情
    public function getOrderDetail()
    {
        $where = [];
        input('id') ? $where['o.id'] = input('id') : $this->err('缺少订单主键');
        $res = model('order')
            ->alias('o')
            ->field('o.*,u.name userName,u.mobile userMobile,au.name workName,au.mobile workMobile, u.IDCards as userIDCards, au.IDCards as workerIDCards,uc.status as contractStatus')
            ->join('user u', 'o.employeeId=u.id', 'left')
            ->join('user_contract uc','uc.orderId=o.id','left')
            ->join('user au', 'o.workId=au.id', 'left')
            ->order('u.id desc')
            ->where($where)
            ->find();
        if($res['contractStatus']==null){
            $res['contractStatus']=0;
        }
        $contract = model('user_contract')->where(['orderId' => input('id')])->find();
        $contract ? true : $contract = [];
        $res['contract'] = $contract;
        $res ? $this->suc($res) : $this->err('获取订单详情失败');
    }

    /**
     * 添加合同
     */
    public function addContract(){
        $data = [];

        input('orderId') ? $data['orderId'] = input('orderId') : true;
        $data['userName'] = input('userName');
        $data['workName'] = input('workName');
        $data['userMobile'] = input('userMobile');
        $data['workMobile'] = input('workMobile');
        $data['startYear'] = input('startYear');
        $data['startMonth'] = input('startMonth');
        $data['startDay'] = input('startDay');
        $data['endYear'] = input('endYear');
        $data['endMonth'] = input('endMonth');
        $data['endDay'] = input('endDay');
        $data['totalAmount'] = input('totalAmount');
        $data['province'] = input('province');
        $data['city'] = input('city');
        $data['district'] = input('district');
        input('street')? $data['street'] = input('street') : true;
        $data['userIDCards'] = input('userIDCards');
        $data['workerIDCards'] = input('workerIDCards');
        input('userSign') ? $data['userSign'] = input('userSign') : true;
        input('workSign') ? $data['workSign'] = input('workSign') : true;

        $result = $this->validate($data, 'order');
        if ($result !== true) {
            $this->err($result);
        }

        Db::startTrans();
        try {
            if(!input('userSign')&& !input('workSign')){
                $this->err('缺少用户签名！');
            }
            if(input('userSign')&& input('workSign')){
                $data['status']=2;
            }
            if(input('userSign')&& !input('workSign')){
                $data['status']=1;
            }
            $res = model('user_contract')->editData($data);
            if($res){
                Db::commit();
                $this->suc($res);
            } else {
                Db::rollback();
                $this->err('合同添加失败！');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('合同添加失败！');
        }

    }

    /**
     * 获取合同
     */
    public function getContractDetail(){
        $where=[];
        input('contractId') ? $where['id']=input('contractId') : $this->err('缺少合同主键');

        $res=model('user_contract')->where($where)->find();
        $res['contractStatus']=$res['status'];
        $res ? $this->suc($res) : $this->err('合同添加失败！');

    }

    /**
     * 添加订单
     */
    public function addOrder()
    {
        $data = [];
        $where = [];
        input('employeeId') ? $data['employeeId'] = input('employeeId') : $this->err('缺少雇主主键');
        input('workId') ? $data['workId'] = input('workId') : $this->err('缺少阿姨主键');
        input('salary') ? $data['orderAmount'] = input('salary') : $this->err('缺少订单金额');
        input('province') ? $data['province'] = input('province') : $this->err('缺少雇主省级地址');
        input('city') ? $data['city'] = input('city') : $this->err('缺少雇主市级地址');
        input('district') ? $data['district'] = input('district') : $this->err('缺少雇主地址');
        input('address') ? $data['address'] = input('address') : $this->err('缺少雇主街道地址');
        $data['orderSn'] = createOrderCode('XB');
        $data['createTime'] = createTime();

        //改变雇佣关系
        input('employeeId') ? $where['employeeId'] = input('employeeId') : $this->err('缺少雇主主键');
        input('workId') ? $where['workId'] = input('workId') : $this->err('缺少阿姨主键');

        // 查找关系表记录
        $res = model('user_relation')->field('id, isHire')->where($where)->find();
        $ur_res = false;

        if ($res['id']) {
            $e_data = [
                'id' => $res['id'],
                'isHire' => 1
            ];
            $ur_res = model('user_relation')->editData($e_data, $e_data['id']);
        } else {
            $e_data['isHire'] = 1;
            $ur_res = model('user_relation')->editData($e_data);
        }
        $rep = model('order')->editData($data);
        $rep ? $this->suc('添加成功！') : $this->err('添加失败！');

    }

    /**
     * 订单支付
     */
    public function payOrder()
    {
        $where = [];
        $l_where = [];
        $data = [];
        input('orderId') ? $where['id'] = input('orderId') : $this->err('缺少订单主键');
        input('payType') ? $data['payType'] = input('payType') : $this->err('缺少支付方式');
        //根据订单主键查找雇主id
        $order = model('order')->where($where)->find();

        if($order['type']==3 && $order['type']==5){
            $cid=$order['workId'];
        }
        else{
            $cid=$order['employeeId'];
        }
        $order ? true : $this->err('订单编码错误！');
        $order['cancelStatus'] == 0 ? true : $this->err('订单已取消！');
        $order['paymentStatus'] == 0 ? true : $this->err('该订单已经支付！');
        //获取是否使用优惠券
        input('isUseCoupon') ? $where['isUseCoupon'] = input('isUseCoupon') : true;
        //优惠金额
        $couponAmount = input('couponAmount');
        $orderAmount = $order['orderAmount'];
        //订单应付价格=订单原价-订单优惠价格
        $totalAmount = $orderAmount - $couponAmount;
        if ($totalAmount <= 0) {
            $this->err('应付金额应大于零');
        }

        // 启动事务
        Db::startTrans();
        try {
            // 判断支付类型 1-钱包 2-微信 3-支付宝 4-后台支付
            switch ($data['payType']) {
                case 1 :
                    $res = model('pay')->pay($cid, $totalAmount, 2, 1, 1, $where['id']);
                    $update_res=model('order')->updateStatus($cid,$order['type']);
                    break;
                case 2:
                    $res = model('pay')->pay($cid, $totalAmount, 2, 2, 1, $where['id']);
                    $update_res=model('order')->updateStatus($cid,$order['type']);
                    break;
                case 4:
                    $res = model('pay')->pay($order['employeeId'], $totalAmount, 2, 4, 1, $where['id']);
                    $update_res=model('order')->updateStatus($cid,$order['type']);
                    break;
                default:
                    $this->err('支付类型错误！');
                    break;
            }
            if(!$res['status']){
                throw new \Exception($res['msg']);
            }
            if(!$update_res['status']){
                throw new \Exception($update_res['msg']);
            }
            //用户消费后自己增加积分
            model('user')->editScore($order['employeeId'], 1, $totalAmount, 2, 1);
            $user = model('user')->field('leaderId')->where(['id' => $order['employeeId']])->find();
            $l_where['id'] = $user['leaderId'];

            //查询上级用户的赏金,魅力分
            $leader = model('user')->field('reward,charm')->where($where)->find();
            //获取已启用的系统配置
            $sy = model('system_config')->where(['status' => 1])->find();
            //一级赏金比率
            if ($leader['charm'] < $sy['secondInviteValue']) {
                model('user')->editScore($l_where['id'], 1, $totalAmount * $sy['firstInviteReward'], 3, 1, $order['employeeId']);
            }
            //二级赏金比率
            if ($sy['secondInviteValue'] <= $leader['charm'] && $leader['charm'] < $sy['thirdInviteValue']) {
                model('user')->editScore($l_where['id'], 1, $totalAmount * $sy['secondInviteReward'], 3, 1, $order['employeeId']);
            }
            //三级赏金比率
            if ($sy['thirdInviteValue'] <= $leader['charm']) {
                model('user')->editScore($l_where['id'], 1, $totalAmount * $sy['thirdInviteReward'], 3, 1, $order['employeeId']);
            }
            // 提交事务
            if($res){
                Db::commit();
                $this->suc('支付成功！');
            } else {
                Db::rollback();
                $this->err('支付失败');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
         //   $this->err($e);
             $this->err('操作失败！');
        }

    }

    /**
     * 后台将订单状态改成已支付
     */
    public function backPayOrder()
    {
        $where = [];
        $o_where = [];
        $o_data = [];
        $data = [];
        $payType = 0;
        input('orderId') ? $o_where['id'] = input('orderId') : $this->err('缺少订单主键');
        input('payType') ? $data['payType'] = input('payType') : $this->err('缺少支付方式');
        $remark = input('remark');
        input('isUseCoupon') ? $where['isUseCoupon'] = input('isUseCoupon') : true;
        $couponAmount = input('couponAmount');         //优惠金额

        // 判断支付类型 1-钱包 2-微信 3-支付宝
        if($data['payType'] != 1 && $data['payType'] != 2 && $data['payType'] != 3){
            $this->err('订单支付类型错误！');
        }

        $o_res = model('order')->field('id,employeeId,orderAmount,couponAmount,isUseCoupon,paymentStatus, cancelStatus')->where($o_where)->find();

        $o_res ? true : $this->err('订单编码错误！');

        $o_res['cancelStatus'] == 0 ? true : $this->err('订单已取消！');

        $o_res['paymentStatus'] == 0 ? true : $this->err('该订单已经支付！');

        $orderAmount = $o_res['orderAmount'];
        $totalAmount = $orderAmount - $couponAmount;       //订单应付价格=订单原价-订单优惠价格
        if ($totalAmount <= 0) {
            $this->err('应付金额应大于零');
        }

        $o_data['paymentStatus'] = 1;
        $o_data['id'] = input('orderId');

        //添加到钱包日志的字段
        $data['moneySn'] = createOrderCode('ZJ');
        $data['targetType'] = 1;                              //1-用户
        $data['targetId'] = $o_res['employeeId'];
        $data['orderId'] = input('orderId');
        $data['orderSrc'] = 4;                             //流水来源 4-后台操作
        $data['moneyType'] = 2;                            //支出
        $data['money'] = $totalAmount;
        $data['payType'] = $o_data['paymentStatus'];
        $data['remark'] = $remark;
        $data['payTime'] = createTime();
        $data['leftMoney'] = 0;

        // 启动事务
        Db::startTrans();
        try {
            model('user_money_log')->editData($data);
            $res = model('order')->editData($o_data, $o_data['id']);
            // 提交事务
            Db::commit();
            $res['status'] ? $this->suc() : $this->err();
          //  $res ? $this->suc('支付成功！') : $this->err('支付失败');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     * 订单批量取消
     */
    public function cancelOrders()
    {
        $where = [];
        $o_arr = input('orderIds/a');
        if (count($o_arr) > 0) {
            $where['id'] = ['in', implode(",", $o_arr)];
        } else {
            $this->err('缺少订单主键');
        }
        $where['cancelStatus'] = 1;

        $res = model('order')->editData($where, $where['id']);
        $res ? $this->suc($res) : $this->err('订单取消失败');

    }

    /**
     * 修改订单金额
     */
    public function editOrderAmount()
    {
        $data = [];
        input('id') ? $data['id'] = input('id') : $this->err('缺少订单主键');
        input('amount') ? $data['totalAmount'] = input('amount') : $this->err('缺少订单金额');
        $data['totalAmount'] < 0 ? $this->err('订单金额需大于0') : true ;

        $res = model('order')->editData($data, $data['id']);
        $res ? $this->suc($res) : $this->err('修改失败！');

    }

    /**
     * 订单作废
     */
    public function cancelOrder()
    {
        $where = [];
        input('orderId') ? $where['id'] = input('orderId') : $this->err('缺少订单主键');
        $where['cancelStatus'] = 1;

        $res = model('order')->editData($where, $where['id']);
        $res ? $this->suc($res) : $this->err('订单取消失败');

    }

    /**
     * 评论订单
     */
    public function commentOrder()
    {
        $data = [];
        input('orderId') ? $data['id'] = input('orderId') : $this->err('缺少订单主键');
        input('commentValue') ? $data['commentValue'] = input('commentValue') : $this->err('缺少评分！');
        $data['commentStatus'] = 1;

        $order = model('order')->where(['id' => $data['id']])->field('id, commentStatus')->find();

        $order['commentStatus'] == 1 ? $this->err('该订单已评价！') : true;

        $res = model('order')->editData($data, $data['id']);
        $res ? $this->suc($res) : $this->err('评论失败');
    }

    /**
     * 审计订单
     */
    public function audit()
    {
        $where = [];
        if (input('idList/a')) {
            array_push($where, ['id', 'in', input('idList/a')]);
        } else {
            $this->err('缺少ID');
        }
        if (input('status')) {
            switch (input('status')) {
                case 1:
                    $res = Db::name('order')
                        ->where($where)
                        ->update(['payStatus' => 1]);
                    if ($res == 0) {
                        $this->err('当前状态已经支付成功，无需修改');
                    } else {
                        $this->suc($res);
                    }
                    break;
                case 2:
                    $res = Db::name('order')
                        ->where($where)
                        ->update(['deliveryStatus' => 1]);
                    if ($res == 0) {
                        $this->err('当前状态已经发货，无需修改');
                    } else {
                        $this->suc($res);
                    }
                    break;
                case 3:
                    $res = Db::name('order')
                        ->where($where)
                        ->update(['cancleStatus' => 1]);
                    if ($res == 0) {
                        $this->err('当前状态已经取消，无需修改');
                    } else {
                        $this->suc($res);
                        break;
                    }
            }

        }
    }
}